// #ifdef APP-PLUS
import voiceRecorderNative from '@/utils/voiceRecorderNative.js'
// #endif
import { lingxinApiService } from '@/service/lingxinApiService'

export default ({ uToastRef, type }) => {
    const voiceSuccess = ref(false)
    const voiceResponse = ref({})

    const startVoice = () => {
        // #ifdef APP-PLUS
        voiceRecorderNative.start()
        voiceRecorderNative.onStop(res => {
            const filePath = res.filePath
            console.log('recorder onStop-平台绝对路径', filePath)
            lingxinVoiceToText(filePath)
        })
        // #endif
    }

    const stopVoice = () => {
        // #ifdef APP-PLUS
        voiceRecorderNative.stop()
        // #endif
    }

    // 语音识别
    const lingxinVoiceToText = filePath => {
        lingxinApiService
            .voiceToText(filePath)
            .then(jsonData => {
                console.log('语音转文本成功：', jsonData)
                if (type === 'manual' && (!jsonData?.object || !jsonData?.param)) {
                    throw new Error("无效的语音！")
                }
                voiceSuccess.value = true
                voiceResponse.value = jsonData
            })
            .catch(e => {
                console.log('语音转文本失败：', e.message)
                voiceSuccess.value = false
                if (uToastRef) {
                    uToastRef.value.show({
                        message: e.message || '语音识别错误!',
                        type: 'error'
                    })
                } else {
                    g_utils.showToast('语音识别错误!')
                }

            })
    }

    return {
        voiceSuccess,
        voiceResponse,
        startVoice,
        stopVoice
    }
}

